package com.bank;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiSelector;
import android.util.DisplayMetrics;
import android.util.Log;

import com.bank.lenovoz5.Z5CGBbank;
import com.entity.BankOrder;
import com.entity.User;
import com.receive.SMSReceiverSend;
import com.show.api.util.StringUtils;
import com.utils.ChatClient;
import com.utils.Constants;
import com.utils.FileHelper;
import com.utils.LogToFile;
import com.utils.UIUtils;

import org.junit.Test;
import org.junit.runner.RunWith;

import java.text.DecimalFormat;

import static android.os.SystemClock.sleep;
import static com.utils.ChatClient.C_updateBalance_W;
import static com.utils.ChatClient.ConfirmOrder;
import static com.utils.ChatClient.getSerialNumber;
import static com.utils.ChatClient.getmap;
import static com.utils.ChatClient.list;
import static com.utils.ChatClient.mapDelete;
import static com.utils.ChatClient.userInfo;
import static com.utils.Constants.orderBankName;

/**
 * 项目名称：yzf_android
 * 类描述：广发银行 ， 不能ROOT
 * 创建人：Administrator
 * 创建时间：2019/6/3 15:35
 * 修改人：Administrator
 * 修改时间：2019/6/3 15:35
 * 修改备注：
 */
@RunWith(AndroidJUnit4.class)
public class CGBbank {
    private String bankName = "CGB";
    private UiDevice mDevice;
    private int screenWidth;
    private int screenHeight;
    private String carrier;
    private float ratio;
    private String sumMoney;

    Context context = InstrumentationRegistry.getTargetContext();
    private SMSReceiverSend sMSReceiverSend;
    private User user;

    private static int[][] xy_123_1920 = new int[][]{
            {300, 1320}, {520, 1320}, {780, 1320},
            {300, 1490}, {520, 1490}, {780, 1490},
            {300, 1660}, {520, 1660}, {780, 1660},
            {520, 1840}
    };
    private static int[][] xy_123_2016 = new int[][]{
            {300, 1415}, {540, 1415}, {785, 1415},
            {300, 1585}, {540, 1585}, {785, 1585},
            {300, 1750}, {540, 1750}, {785, 1750},
            {540, 1925}
    };
    private static int[][] xy_123_2102 = new int[][]{
            {300, 1415}, {540, 1415}, {785, 1415},
            {300, 1585}, {540, 1585}, {785, 1585},
            {300, 1750}, {540, 1750}, {785, 1750},
            {540, 1925}
    };
    private static int[][] xy_123;

    @Test
    public void demo() throws UiObjectNotFoundException, InterruptedException {
        LogToFile.init(InstrumentationRegistry.getTargetContext(), Constants.PROT);
        Constants.CODE = "";
        mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
        UIUtils.initServicePermission(mDevice);
        mDevice.pressHome();
        mDevice.pressHome();
        UiObject mTV_bank_icon = mDevice.findObject(new UiSelector().text("广发银行"));
        mTV_bank_icon.click();
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_8) {
                showMsg("升级弹窗查找超时...");
                break;
            }
            UiObject mBT_dialog_left = mDevice.findObject(new UiSelector().resourceId("com.cgb.mobilebank.common:id/tv_left")
                    .text("稍后再说"));
            if (mBT_dialog_left.exists()) {
                showMsg("关闭升级弹窗...");
                mBT_dialog_left.click();
                break;
            }
        }
        /***************执行联想Z5类*******************/
        if (android.os.Build.MODEL.equals("Lenovo L78011")) {
            showLog("联想Z5设备");
            new Z5CGBbank(mDevice);
            return;
        }
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;
        carrier = android.os.Build.MODEL;
        ratio = screenWidth / 720f;
        LogToFile.d("手机分辨率：", "手机分辨率" + carrier + "-----" + screenWidth + "----" + screenHeight + "----" + ratio);
        Constants.getsTheModelAndVersionNumberAndVersionName(context, "广发银行");
        keyPhone();

        initBroadcast();
        Thread.sleep(ChatClient.overtime_10);
        while (true) {
            UiObject mTV_ransfert = mDevice.findObject(new UiSelector().text("转账汇款").resourceId("com.cgb.mobilebank.sit" +
                    ".launcher:id/tv_name"));
            if (mTV_ransfert.exists()) {
                showMsg("点击转账汇款");
                mTV_ransfert.click();
                ChatClient.start();
                //获取账号信息
                ChatClient.begintime = System.currentTimeMillis();//开始时间
                while (true) {
                    long nowtime1 = System.currentTimeMillis();
                    if ((nowtime1 - ChatClient.begintime) > ChatClient.overtime) {
                        ChatClient.timer(LogToFile.getMethodName(), ChatClient.errorStr);
                        return;
                    }
                    //请求登录信息
                    if (userInfo.equals("")) {
                        ChatClient.msg("<YZF>{'header':'" + ChatClient.M_GET_BANK_LOGIN_INFO_P +
                                "'}</YZF>");
                        sleep(5000);
                    } else {
                        user = new User();
                        String[] res = userInfo.split(" ");
                        for (int i = 0; i < res.length; i++) {
                            switch (i) {
                                case 0:
                                    user.setUserName(res[0]);
                                    break;
                                case 1:
                                    user.setPwd(res[1]);
                                    break;
                                case 2:
                                    user.setBankpwd(res[2]);
                                    break;
                                case 3:
                                    user.setUsbPayPwd(res[3]);
                                    break;
                                case 4:
                                    user.setUseType(res[4]);
                                    break;
                                case 5:
                                    user.setBankId(res[5]);
                                    break;
                            }
                        }
                        break;
                    }
                }
                break;
            }
        }
        sleep(2000);
        Login();
    }

    //键盘适配
    private void keyPhone() {
        switch (screenHeight) {
            case 1920:
                xy_123 = xy_123_1920;
                break;
            case 2016:
                xy_123 = xy_123_2016;
                break;
            case 2102:
                xy_123 = xy_123_2102;
                break;
        }
    }

    /**
     * 配置短信广播
     */
    private void initBroadcast() {
        //动态注册短信广播
        Constants.MOBILE_BOB = "95508";
        sMSReceiverSend = new SMSReceiverSend();
        Constants.CODE = "";
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.SMS_ACTION);
        filter.addAction("net.blogjava.mobile.SMSto");
        // 设置优先级 不然监听不到短信
        filter.setPriority(1000);
        context.registerReceiver(sMSReceiverSend, filter);
        Intent intent = new Intent();
        intent.setAction("com.tiantian.SEND_TO");
        context.sendBroadcast(intent);
    }

    private void Login() throws UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_60) {
                ChatClient.timer(LogToFile.getMethodName(), ChatClient.loginError);
                break;
            }
            UiObject mET_paw;
            if (screenHeight == 1440) {
                UiObject mET_paw_title = mDevice.findObject(new UiSelector().resourceId("com.cgb.mobilebank.android.login:id/tv_name")
                        .text("登录密码"));
                mET_paw = mET_paw_title.getFromParent(new UiSelector().className("android.widget.EditText").index(1));
            } else {
                mET_paw = mDevice.findObject(new UiSelector().className("android.widget.EditText").text("请输入登录密码"));
            }
            if (mET_paw.exists()) {
                showMsg("点击登录密码");
                mET_paw.click();
                sleep(2000);
                clickPaw();
                break;
            }
        }
        waitTransfer();
    }

    /**
     * 进入转账页面
     */
    private void waitTransfer() throws UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_60) {
                ChatClient.timer(LogToFile.getMethodName(), ChatClient.loginError);
                return;
            }
            UiObject mTV_transfer = mDevice.findObject(new UiSelector().className("android.view.View").descriptionContains("银行卡转账"));
            if (mTV_transfer.exists()) {
                //登录成功
                ChatClient.loginS();
                break;
            }
        }
        sleep(ChatClient.overtime_5);
        remittancePage();
    }


    /**
     * 更新余额
     */
    private void updateBalance(String balance) {
        showMsg("可用余额===" + balance);
        if (!StringUtils.isEmpty(balance)) {
            String b = balance.replaceAll("元", "");
            b = b.replaceAll(",", "");
            C_updateBalance_W(Double.parseDouble(b));
            sleep(3000);
        }
    }

    /**
     * 分配业务功能
     */
    private void assignFeatures() throws UiObjectNotFoundException {
        //订单判断
        if (list.size() > 0) {
            orderBankName = Constants.getBank(list.get(0).getBankName(), "CGB");
            if (ConfirmOrder) {
                //进入查账
                showMsg("开始查账流程");
                auditOrder();
            } else {
                //进入转账
                showMsg("进行转账页");
                remittancePage();
            }
        } else {
            showMsg("转账页，等待订单");
            remittancePage();
        }
    }

    /**
     * 查账
     */
    private void auditOrder() throws UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtimeLogin) {
                ChatClient.timer(LogToFile.getMethodName(), ChatClient.layoutLoadError);
                return;
            }
            UiObject mTV_notes = mDevice.findObject(new UiSelector().className("android.view.View").descriptionContains("转账记录"));
            //判断是否进入转账页面
            if (mTV_notes.exists()) {
                showMsg("进入查账页面");
                mTV_notes.click();
                sleep(ChatClient.overtime_3);
                break;
            }
        }

        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtimeLogin) {
                ChatClient.timer(LogToFile.getMethodName(), ChatClient.layoutLoadError);
                return;
            }
            UiObject mWV = mDevice.findObject(new UiSelector().className("android.webkit.WebView").descriptionContains("转账记录"));
            //判断是否进入转账页面
            if (mWV.exists()) {
                UiObject child2;
                if (screenHeight == 1440) {
                    child2 = mWV.getChild(new UiSelector().className("android.view.View").index(6));
                } else {
                    UiObject child = mWV.getChild(new UiSelector().className("android.view.View").index(2));
                    UiObject child1 = child.getChild(new UiSelector().className("android.view.View").index(0));
                    child2 = child1.getChild(new UiSelector().className("android.view.View").index(1));
                }
                if (child2.exists()) {
                    showMsg("点击进入第一条转账记录");
                    child2.click();
                    sleep(5000);
                    break;
                }
            }
        }

        String name = null, money = null, bankInfo = null, status = null;
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtimeLogin) {
                ChatClient.timer(LogToFile.getMethodName(), ChatClient.layoutLoadError);
                return;
            }
            UiObject mWV = mDevice.findObject(new UiSelector().className("android.webkit.WebView").descriptionContains("转账记录查询"));
            //判断是否进入转账页面
            if (mWV.exists()) {
                UiObject mTV_name = mWV.getChild(new UiSelector().className("android.view.View").index(0));
                UiObject mTV_money = mWV.getChild(new UiSelector().className("android.view.View").index(1));
                UiObject mTV_bankInfo, mLV;
                if (screenHeight == 1440) {
                    mTV_bankInfo = mWV.getChild(new UiSelector().className("android.view.View").index(2));
                    mLV = mWV.getChild(new UiSelector().className("android.widget.ListView").index(3));
                } else {
                    mTV_bankInfo = mWV.getChild(new UiSelector().className("android.view.View").index(3));
                    mLV = mWV.getChild(new UiSelector().className("android.widget.ListView").index(4));
                }
                if (StringUtils.isEmpty(name) && mTV_name.exists()) {
                    name = mTV_name.getContentDescription();
                }
                if (StringUtils.isEmpty(money) && mTV_money.exists()) {
                    money = mTV_money.getContentDescription();
                }
                if (StringUtils.isEmpty(bankInfo) && mTV_bankInfo.exists()) {
                    bankInfo = mTV_bankInfo.getContentDescription();
                }
                if (StringUtils.isEmpty(status) && mLV.exists()) {
                    UiObject mTV_status = mLV.getChild(new UiSelector().className("android.view.View").index(3));
                    if (StringUtils.isEmpty(status) && mTV_status.exists()) {
                        status = mTV_status.getContentDescription();
                    }
                }
                if (!StringUtils.isEmpty("name") && !StringUtils.isEmpty("money") && !StringUtils.isEmpty("bankInfo") &&
                        !StringUtils.isEmpty("status")) {
                    //                    showMsg("查询到转账订单，name=" + name + ",money=" + money + ",bankInfo=" + bankInfo + ",status=" + status);
                    break;
                }
            }
        }

        String json = null;
        String mobileD = null;
        money = money.replaceAll("¥", "");
        money = money.replaceAll("元", "");
        money = money.replaceAll(",", "");
        String bankNo = bankInfo.substring(bankInfo.indexOf("(") + 1, bankInfo.indexOf(")"));
        bankNo = bankNo.replaceAll(" ", "");
        status = status.replace("转账状态 ", "");
        BankOrder bankOrder = list.get(0);

        //"userName":"周悦", "bankName":"中国建设银行", "bankNo":"6217004220024054177", "money":2.0, "purpose":"", "type":1,"openingBank": ""
        showMsg("查询到转账订单，name=" + bankOrder.getUserName().equals(name) + ",money=" + (Double.parseDouble(bankOrder.getMoney()) == Double
                .parseDouble(money)) + ",bankNo=" + bankOrder.getBankNo().equals(bankNo) + ",status=" + status);
        int state = 1;
        if (bankOrder.getUserName().equals(name) && Double.parseDouble(bankOrder.getMoney()) == Double.parseDouble(money) &&
                bankOrder.getBankNo().equals(bankNo)) {
            showMsg("订单数据匹配上");
            if (Constants.getStr(status) == 0) {
                showMsg("状态：成功");
                DecimalFormat formater = new DecimalFormat("#0.##");
                sumMoney = formater.format(Double.parseDouble(sumMoney));
                state = 0;
            } else if (status.contains("失败")) {
                state = 1;
            }
            json = "'order':'" + list.get(0).getOrder() + "','balance':'" + sumMoney + "','state':" + state + ",'type':1";
            mobileD = "'devices':'" + getSerialNumber() + "','prot':'" + Constants.PROT + "','phoneModel':'广发银行'," +
                    "'info':'" + status + "'";
        } else {
            String sumMoneyFile = user.getUserName() + bankName + "_sumMoney.txt";
            String oldMoney = FileHelper.readSDFile(sumMoneyFile);
            switch (Constants.changeInAmount(bankName, oldMoney, sumMoney, list.get(0).getMoney())) {
                case "0":
                    json = "'order':'" + list.get(0).getOrder() + "','balance':'" + sumMoney + "','state':0,'type':1";
                    mobileD = "'devices':'" + getSerialNumber() + "','prot':'" + Constants.PROT + "','phoneModel':'广发银行'," +
                            "'info':'交易成功'";
                    break;
                case "1":
                    json = "'order':'" + list.get(0).getOrder() + "','balance':'" + sumMoney + "','state':1,'type':1";
                    mobileD = "'devices':'" + getSerialNumber() + "','prot':'" + Constants.PROT + "','phoneModel':'广发银行'," +
                            "'info':'交易待处理...'";
                    break;
                case "4":
                    json = "'order':'" + list.get(0).getOrder() + "','balance':'" + sumMoney + "','state':4,'type':1";
                    mobileD = "'devices':'" + getSerialNumber() + "','prot':'" + Constants.PROT + "','phoneModel':'广发银行'," +
                            "'info':'未查到条目'";
                    break;
            }
        }
        ChatClient.msg("<YZF>{'header':'" + ChatClient.S_CONFIRM_TRADE_RESULT_C + "'," + json + "," + mobileD + "}</YZF>");

        mapDelete(list.get(0).getOrder());

        getmap();

        backTransferMainPage();

        assignFeatures();

    }

    /**
     * 转账页
     */
    private void remittancePage() throws UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_60) {
                ChatClient.timer(LogToFile.getMethodName(), ChatClient.error);
                return;
            }
            UiObject zhuanzhang = mDevice.findObject(new UiSelector().className("android.view.View").descriptionContains("银行卡转账"));
            //判断是否进入转账页面
            if (zhuanzhang.exists()) {
                showMsg("进入银行卡转账页面");
                zhuanzhang.click();
                sleep(ChatClient.overtime_2);
            }

            UiObject dialogContent = mDevice.findObject(new UiSelector().resourceId("com.cgb.mobilebank.common:id/tv_content").text
                    ("网络繁忙或未连接"));
            //判断是否进入转账页面
            if (dialogContent.exists()) {
                UiObject mBT_dialog_close = mDevice.findObject(new UiSelector().resourceId("com.cgb.mobilebank.common:id/tv_right").text("确定"));
                if (mBT_dialog_close.exists()) {
                    showMsg("关闭网络弹窗");
                    mBT_dialog_close.click();
                    sleep(ChatClient.overtime_2);
                    mDevice.pressBack();
                    remittancePage();
                    return;
                }
            }

            UiObject mTV_balance1 = mDevice.findObject(new UiSelector().className("android.webkit.WebView").descriptionContains("银行卡转账"));
            UiObject mTV_balance2 = mDevice.findObject(new UiSelector().className("android.webkit.WebView").text("银行卡转账"));
            if (mTV_balance1.exists()) {
                UiObject mTV_balance;
                mTV_balance = mTV_balance1.getChild(new UiSelector().instance(5).className("android.view.View"));
                if (mTV_balance.exists()) {
                    sumMoney = mTV_balance.getContentDescription().replace("元", "");
                    sumMoney = sumMoney.replaceAll(",", "");
                    if (!StringUtils.isEmpty(sumMoney)) {
                        showMsg("更新余额===" + sumMoney);
                        updateBalance(mTV_balance.getContentDescription());
                        if (!ChatClient.existOrder()||(ChatClient.existOrder() && !ConfirmOrder)) {
                            showMsg("本地保存余额2");
                            String sumMoneyFile = user.getUserName() + bankName + "_sumMoney.txt";
                            FileHelper.saveMoneySDFile(false, sumMoney, sumMoneyFile);
                        }

                        break;
                    } else {
                        showMsg("获取金额为===" + sumMoney);
                    }
                }
            } else if (mTV_balance2.exists()) {
                UiObject mTV_balance = mTV_balance2.getChild(new UiSelector().instance(5).className("android.view.View"));
                if (mTV_balance.exists()) {
                    sumMoney = mTV_balance.getContentDescription().replace("元", "");
                    sumMoney = sumMoney.replaceAll(",", "");
                    if (!StringUtils.isEmpty(sumMoney)) {
                        showMsg("更新余额===" + sumMoney);
                        updateBalance(mTV_balance.getContentDescription());
                        if (ChatClient.existOrder() && !ConfirmOrder) {
                            showMsg("本地保存余额4");
                            String sumMoneyFile = user.getUserName() + bankName + "_sumMoney.txt";
                            FileHelper.saveMoneySDFile(false, sumMoney, sumMoneyFile);
                        }
                    } else {
                        showMsg("获取金额为===" + sumMoney);
                    }
                }
            }
        }
        /*****************判断余额是否够余额是否够本次订单使用********************/
        if (!ChatClient.waitExistOrder(ChatClient.overtime_60)) {
            refreshPage();
            assignFeatures();
            return;
        } else {
            sleep(ChatClient.overtime_2);
            if (ConfirmOrder) {
                showMsg("有订单，返回上页查账");
                mDevice.pressBack();
                assignFeatures();
                return;
            }
            if (!StringUtils.isEmpty(sumMoney)) {
                showMsg("比对余额是否够本次订单使用");
                sumMoney = sumMoney.replace("元", "");
                sumMoney = sumMoney.replaceAll(",", "");
                if (ChatClient.existOrder() && !ConfirmOrder) {
                    showMsg("本地保存余额");
                    String sumMoneyFile = user.getUserName() + bankName + "_sumMoney.txt";
                    FileHelper.saveMoneySDFile(false, sumMoney, sumMoneyFile);
                }
                boolean b = comparisonBalance(sumMoney);
                if (b) {
                    showMsg("余额是够本次订单使用,继续转账");
                } else {
                    showMsg("余额不够本次订单使用返回上页");
                    mDevice.pressBack();
                    return;
                }
            }
        }


        if (phoneScript()) {
            sleep(2000);
            while (true) {
                UiObject mBT_next = mDevice.findObject(new UiSelector().className("android.widget.Button").descriptionContains("下一步"));
                if (mBT_next.exists()) {
                    showMsg("点击下一步");
                    mBT_next.click();
                    sleep(3000);
                    break;
                }
            }
            SMSFlag = 1;
            yanZhengPsw();
        }
    }

    /**
     * 重选出款银行卡 刷新界面
     *
     * @throws UiObjectNotFoundException
     */
    private void refreshPage() throws UiObjectNotFoundException {
        showMsg("点击《转出账号》");
        mDevice.click(330, 300);
        sleep(ChatClient.overtime_2);
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_5) {
                showMsg("超时选择转出账号");
                mDevice.click(540, 1810);
                break;
            }
            UiObject mTV_bankNo = mDevice.findObject(new UiSelector().resourceId("com.cgb.mobilebank.common:id/tv_item").index(0));
            if (mTV_bankNo.exists()) {
                showMsg("选择银行卡...");
                mTV_bankNo.click();
                break;
            }
        }
        sleep(ChatClient.overtime_2);
    }

    /**
     * 验证码与取款密码验证
     */
    int SMSFlag = 1;

    private void yanZhengPsw() throws UiObjectNotFoundException {
        ChatClient.addWorkTime(ChatClient.overtime_60);
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_60) {
                ChatClient.timer(LogToFile.getMethodName(), ChatClient.error);
                break;
            }
            UiObject mBT_requestSMS = mDevice.findObject(new UiSelector().className("android.view.View").descriptionContains("获取验证码"));
            if (mBT_requestSMS.exists()) {
                showMsg("进入安全验证页面，点击获取验证码，第" + SMSFlag + "次请求短信");
                mBT_requestSMS.click();
                break;
            }
            sleep(ChatClient.overtime_1);
        }
        if (SMSFlag > 1 && !StringUtils.isEmpty(ChatClient.smsCode.getSmscode())) {
            while (true) {
                long nowtime = System.currentTimeMillis();
                if ((nowtime - ChatClient.begintime) > ChatClient.overtime_30) {
                    ChatClient.timer(LogToFile.getMethodName(), "安全验证页面超时...");
                    break;
                }
                UiObject mV = mDevice.findObject(new UiSelector().descriptionContains("短信验证码").index(0));
                if (mV.exists()) {
                    showMsg("第" + SMSFlag + "次请求短信");
                    UiObject mV2 = mV.getFromParent(new UiSelector().index(1));
                    if (mV2.exists()) {
                        showMsg("点击短信输入栏...");
                        mV2.click();
                        sleep(ChatClient.overtime_1);
                        UiObject mV3 = mV2.getChild(new UiSelector().className("android.view.View").index(1));
                        if (mV3.exists()) {
                            showMsg("删除之前输入验证码...");
                            mV3.click();
                            sleep(ChatClient.overtime_2);
                            break;
                        }
                    }
                }
            }
        }

        //短信获取成功
        boolean SMS_success = true;
        sleep(ChatClient.overtime_15);
        //无卡机短信填充
        if (!user.getUseType().equals("1")) {
            SMS_success = simulatorSMS();
        }
        String dialog_content;
        if (SMS_success) {
            while (true) {
                UiObject mBT_submit = mDevice.findObject(new UiSelector().className("android.widget.Button")
                        .descriptionContains("提交"));
                showMsg("获取提交");
                if (mBT_submit.isClickable() && mBT_submit.exists()) {
                    showMsg("进入安全验证页面,输入取款密码");
                    mBT_submit.click();
                    sleep(3000);
                    break;
                }
                sleep(ChatClient.overtime_1);
            }

            /*******************点击银行密码*********************/
            char[] chars = user.getBankpwd().toCharArray();
            for (int i = 0; i < chars.length; i++) {
                clickKey("android.widget.Button", String.valueOf(chars[i]));
            }
            sleep(ChatClient.overtime_2);
            /****************两次判定dialog弹窗，第一次是同账号二次转账，第二次是转账信息错误*******************/
            dialog_content = closeDialog();
            if (dialog_content.equals("next")) {
                dialog_content = closeDialog();
            }
        } else {
            dialog_content = "短信验证错误";
        }
        showMsg("dialog_content---" + dialog_content + "---SMSFlag---" + SMSFlag);
        /************继续转账逻辑**************/
        if (dialog_content.equals("next")) {
            sleep(ChatClient.overtime_2);
            balanceResult();
            assignFeatures();
        } else if (SMSFlag < 3 && !dialog_content.contains("状态异常") && !dialog_content.contains("户名不符") && !dialog_content.contains("账号不存在")) {
            if (dialog_content.equals("短信验证码错误，请重新输入") || dialog_content.equals("短信验证码错误次数过多，请重新获取") || dialog_content.equals
                    ("短信验证码错误") || StringUtils.isEmpty(ChatClient.smsCode.getSmscode())) {
                sleep(ChatClient.overtime_1);
                SMSFlag += 1;
                yanZhengPsw();
            }
        } else {
            sleep(1000);
            SMSFlag = 1;
            sendResultInfo(dialog_content);
            backTransferMainPage();
            assignFeatures();
        }
    }

    /**
     * 手机适配
     */
    private boolean phoneScript() throws UiObjectNotFoundException {
        while (true) {
            UiObject mET_bankNo = mDevice.findObject(new UiSelector().className("android.widget.EditText").text("请输入收款人的卡号"));
            //判断是否进入转账页面
            if (mET_bankNo.exists()) {
                mET_bankNo.click();
                sleep(ChatClient.overtime_1);
                showMsg("填入收款银行");
                mET_bankNo.setText(list.get(0).getBankNo());
                sleep(ChatClient.overtime_2);
                break;
            }
        }

        while (true) {
            UiObject mET_name = mDevice.findObject(new UiSelector().className("android.widget.EditText").text("请输入收款人姓名"));
            //判断是否进入转账页面
            if (mET_name.exists()) {
                mET_name.click();
                sleep(2000);
                showMsg("填入收款人" + list.get(0).getUserName());
                mET_name.setText(list.get(0).getUserName());
                sleep(2000);
                break;
            }
        }

        //判定银行
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_5) {
                showMsg("===自动识别成功===");
                break;
            }
            UiObject mV_bank = mDevice.findObject(new UiSelector().className("android.view.View").descriptionContains("收款银行"));
            //判断是否进入转账页面
            if (mV_bank.exists()) {
                UiObject mV_bankName = mV_bank.getFromParent(new UiSelector().index(1).className("android.view.View"));
                if (mV_bankName.exists()) {
                    String bankName = mV_bankName.getContentDescription();
                    if (bankName.contains("请选择开户行")) {
                        showMsg("进入银行选择页面");
                        mV_bankName.click();
                        if (addBank()) {
                            showMsg("点击跳转选择收款银行页");
                            sleep(2000);
                            break;
                        } else {
                            return false;
                        }
                    }
                }
            }
        }

        while (true) {
            UiObject mET_amount = mDevice.findObject(new UiSelector().className("android.widget.EditText").text("请输入转账金额"));
            if (mET_amount.exists()) {
                showMsg("输入转账金额");
                mET_amount.click();
                sleep(2000);
                clickAmount();
                break;
            }
        }
        return true;
    }

    private boolean addBank() throws UiObjectNotFoundException {
        while (true) {
            UiObject mET_inputBankName = mDevice.findObject(new UiSelector().resourceId("com.cgb.mobilebank.sit" +
                    ".launcher:id/edit_search").text("请输入银行名称"));
            if (mET_inputBankName.exists()) {
                showMsg("填入搜索框");
                mET_inputBankName.setText(orderBankName);
                sleep(2000);
                break;
            }
        }

        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_15) {
                String mobileD = "'devices':'" + getSerialNumber() + "','prot':'" + Constants.PROT + "'," +
                        "'phoneModel':'广发银行'," +
                        "'info':'银行名错误'";
                String json = "'order':'" + list.get(0).getOrder() + "','balance':'" + sumMoney + "','state':1," +
                        "'type':1";
                ChatClient.msg("<YZF>{'header':'" + ChatClient.M_SEND_TRADE_RESULT_P + "'," + json + "," + mobileD +
                        "}</YZF>");
                //删除处理过的订单
                mapDelete(list.get(0).getOrder());
                getmap();
                backTransferMainPage();
                assignFeatures();
                return false;
            }
            UiObject mRV_bankList = mDevice.findObject(new UiSelector().resourceId("com.cgb.mobilebank.sit" +
                    ".launcher:id/back_list_recycleview"));
            if (mRV_bankList.exists()) {
                UiObject mLL_item = mRV_bankList.getChild(new UiSelector().resourceId("com.cgb.mobilebank.sit.launcher:id/tv_bank_name")
                        .text(orderBankName));
                if (mLL_item.exists()) {
                    showMsg("点击银行条目");
                    mLL_item.click();
                    sleep(2000);
                    break;
                }
            }
        }
        return true;
    }

    /**
     * 无卡机短信验证码处理
     */

    private boolean simulatorSMS() throws UiObjectNotFoundException {
        ChatClient.requestSMSCode(user.getUserName(), user.getBankId());
        while (true) {
            UiObject mBT_putSMS = mDevice.findObject(new UiSelector().className("android.widget.EditText").text("请输入短信验证码"));
            if (mBT_putSMS.exists()) {
                showMsg("无卡机输入短信验证码");
                if (!user.getUseType().equals("1")) {
                    showLog("收到短信验证码：" + ChatClient.smsCode.getSmscode());
                    if (!StringUtils.isEmpty(ChatClient.smsCode.getSmscode())) {
                        mBT_putSMS.click();
                        sleep(1000);
                        mDevice.click(75, 1920);
                        sleep(2000);
                        setClickNum(ChatClient.smsCode.getSmscode());
                        sleep(2000);
                        return true;
                    } else {
                        showMsg("收到null验证码");
                        return false;
                    }
                }
            }
        }
    }

    private String closeDialog() throws UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_5) {
                showMsg("没有确定弹窗");
                return "next";
            }
            UiObject mTV_dialog_content = mDevice.findObject(new UiSelector().resourceId("com.cgb.mobilebank.common:id/tv_content"));
            UiObject mTV_dialog_right = mDevice.findObject(new UiSelector().resourceId("com.cgb.mobilebank.common:id/tv_right"));
            if (mTV_dialog_right.exists()) {
                String text = mTV_dialog_right.getText();
                if (text.equals("继续转账")) {
                    showMsg("弹出确认dialog");
                    mTV_dialog_right.click();
                    showMsg("点掉确认dialog");
                    sleep(2000);
                    return "next";
                } else if (text.equals("确定")) {
                    if (mTV_dialog_content.exists()) {
                        String mTV_content = mTV_dialog_content.getText();
                        if (!StringUtils.isEmpty(mTV_content)) {
                            showMsg("错误原因：" + mTV_content);
                            mTV_dialog_right.click();
                            showMsg("点击关闭错误弹窗");
                            return mTV_content;
                        }
                    }
                }
            }
        }
    }

    /**
     * 转账结果页
     */
    public void balanceResult() throws UiObjectNotFoundException {
        UiObject mBT = null;
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_60) {
                ChatClient.timer(LogToFile.getMethodName(), ChatClient.error);
                return;
            }
            UiObject mV_close = mDevice.findObject(new UiSelector().className("android.view.View").descriptionContains("取消"));
            if (mV_close.exists()) {
                mV_close.click();
            }
            mBT = mDevice.findObject(new UiSelector().className("android.widget.Button").descriptionContains("继续转账"));
            if (mBT.exists()) {
                showMsg("汇款结果页加载完成");
                sleep(1000);
                break;
            }
        }

        while (true) {
            UiObject mWV = mDevice.findObject(new UiSelector().className("android.webkit.WebView").descriptionContains("转账汇款"));
            UiObject child = null;
            if (mWV.exists()) {
                UiObject child1 = mWV.getChild(new UiSelector().className("android.view.View").index(0));
                child = child1.getChild(new UiSelector().className("android.view.View").instance(2));
                if (child.exists()) {
                    String s = child.getContentDescription();
                    if (!StringUtils.isEmpty(s)) {
                        showMsg("转账结果：" + s);
                        sendResultInfo(s);
                        sleep(3000);
                        showMsg("点击继续转账");
                        mBT.click();
                        sleep(ChatClient.overtime_2);
                        break;
                    }
                }
            }
        }
    }

    /**
     * 上报转账结果
     ***/
    private void sendResultInfo(String info) {
        if (Constants.getStr(info) == 0) {
            DecimalFormat formater = new DecimalFormat("#0.##");
            sumMoney = formater.format(Double.parseDouble(sumMoney) - Double.parseDouble(list.get(0).getMoney()));
            showMsg("保存余额...");
            String sumMoneyFile = user.getUserName() + bankName + "_sumMoney.txt";
            FileHelper.saveMoneySDFile(false, sumMoney, sumMoneyFile);
        }
        String mobileD = "'devices':'" + getSerialNumber() + "','prot':'" + Constants.PROT + "'," +
                "'phoneModel':'广发银行'," + "'info':'" + info + "'";
        String json = "'order':'" + list.get(0).getOrder() + "','balance':'" + sumMoney + "'," +
                "'state':" + Constants.getStr(info) + ",'type':1";
        ChatClient.msg("<YZF>{'header':'" + ChatClient.M_SEND_TRADE_RESULT_P + "'," + json + ","
                + mobileD + "}</YZF>");
        //删除处理过的订单
        mapDelete(list.get(0).getOrder());
        getmap();
    }

    /**
     * 比对余额是否够此笔订单
     */
    private boolean comparisonBalance(String balance) {
        boolean b = true;
        Double balanceMoney = Double.parseDouble(balance);
        Double orderMoney = Double.parseDouble(list.get(0).getMoney());
        if (balanceMoney < orderMoney) {
            b = false;
            String mobileD = "'devices':'" + getSerialNumber() + "','prot':'" + Constants.PROT + "'," +
                    "'phoneModel':'广发银行'," +
                    "'info':'账户余额不足'";
            String json = "'order':'" + list.get(0).getOrder() + "','balance':'" + balanceMoney + "','state':1,'type':1";
            ChatClient.msg("<YZF>{'header':'" + ChatClient.M_SEND_TRADE_RESULT_P + "'," + json + "," + mobileD +
                    "}</YZF>");
            //删除处理过的订单
            mapDelete(list.get(0).getOrder());
            getmap();
        }
        return b;
    }

    /**
     * 点击转账金额
     */
    private void clickAmount() throws UiObjectNotFoundException {
        String view_class = "android.widget.Button";
        String money = list.get(0).getMoney();
        char[] chars = money.toCharArray();
        for (int i = 0; i < money.length(); i++) {
            String key = String.valueOf(chars[i]);
            if (key.equals(".")) {
                view_class = "android.widget.TextView";
            } else {
                view_class = "android.widget.Button";
            }
            clickKey(view_class, key);
        }
        while (true) {
            UiObject mTV = mDevice.findObject(new UiSelector().className("android.widget.TextView").text("确定"));
            if (mTV.exists()) {
                showMsg("点击金额键盘确认");
                mTV.click();
                sleep(ChatClient.overtime_2);
                mDevice.drag(70, 400, 70, 930, 20);
                sleep(ChatClient.overtime_2);
                break;
            }
        }
        while (true) {
            UiObject mV = mDevice.findObject(new UiSelector().descriptionContains("转账金额").className("android.view.View"));
            if (mV.exists()) {
                UiObject mVV = mV.getFromParent(new UiSelector().className("android.view.View").index(2));
                if (mVV.exists()) {
                    UiObject mET_money = mVV.getChild(new UiSelector().className("android.widget.EditText").index(0));
                    if (mET_money.exists()) {
                        String moneyText = mET_money.getText().trim();
                        moneyText = moneyText.replaceAll(",", "");
                        if (!moneyText.isEmpty()) {
                            if (moneyText.contains("请输入转账金额")) {
                                mET_money.click();
                                clickAmount();
                                break;
                            } else if (Double.parseDouble(money) == Double.parseDouble(moneyText)) {
                                showMsg("输入金额正确");
                                break;
                            } else {
                                showMsg("输入金额错误");
                                mET_money.click();
                                sleep(ChatClient.overtime_1);
                                mDevice.click(1020, 1000);
                                sleep(1000);
                                clickAmount();
                                break;
                            }
                        }
                    }
                }
            }
        }
    }


    boolean isNumKey = true;

    /**
     * 点击密码
     *
     * @throws UiObjectNotFoundException
     */
    private void clickPaw() throws UiObjectNotFoundException {
        char[] chars = user.getPwd().toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            String s = String.valueOf(c);
            if (isNumKey && !isNumeric(s)) {
                clickKey("android.widget.TextView", "ABC");
                isNumKey = false;
            }
            clickKey("android.widget.TextView", s);
        }
        while (true) {
            UiObject mTV_end = mDevice.findObject(new UiSelector().className("android.widget.TextView").text("完成"));
            if (mTV_end.exists()) {
                showMsg("收起键盘，登录银行");
                mTV_end.click();
                sleep(ChatClient.overtime_2);
                break;
            }
        }
    }

    /**
     * 点击键盘按键
     *
     * @param key
     * @throws UiObjectNotFoundException
     */
    private void clickKey(String view_class, String key) throws UiObjectNotFoundException {
        showMsg("点击--*");
        while (true) {
            UiObject mTV_key = mDevice.findObject(new UiSelector().className(view_class).text(key));
            if (mTV_key.exists()) {
                mTV_key.click();
                sleep(1000);
                break;
            }
        }
    }

    /**
     * 返回转账主页
     */
    private void backTransferMainPage() {
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_5) {
                showMsg("返回上页");
                mDevice.pressBack();
                ChatClient.begintime = System.currentTimeMillis();
            }
            UiObject mTV = mDevice.findObject(new UiSelector().className("android.view.View").descriptionContains("通讯录转账"));
            if (mTV.exists()) {
                showMsg("以返回转账主页");
                return;
            }
        }
    }


    /**
     * 字母和数字键盘的切换
     *
     * @param checkStr
     * @return
     */
    private static boolean isNumeric(String checkStr) {
        try {
            Integer.parseInt(checkStr);
            return true;
        } catch (NumberFormatException err) {
            return false;
        }
    }

    /**
     * 模拟点击数字键盘
     *
     * @throws Exception
     */
    public void setClickNum(String clickNum) {
        char[] num = "1234567890".toCharArray();//char数组
        char[] bankNum = clickNum.toCharArray();//char数组
        for (int j = 0; j < bankNum.length; j++) {
            for (int i = 0; i < num.length; i++) {
                if (num[i] == bankNum[j]) {
                    showMsg("点击---" + bankNum[j] + "----" + xy_123[i][0] + "----" + xy_123[i][1]);
                    mDevice.click((xy_123[i][0]), (xy_123[i][1]));
                    sleep(1000);
                    break;
                }
            }
        }
        mDevice.click(500, 1000);
    }

    public void showMsg(String msg) {
        LogToFile.showLog("广发银行", msg);
    }

    public void showLog(String msg) {
        Log.i("广发银行" + "==", "===《" + msg + "》===");
    }
}
